﻿#if __ANDROID__
#region File and License Information
/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2012, Outcoder. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>2013-01-01 11:32:08Z</CreationDate>
</File>
*/
#endregion

using Android.App;
using Android.Content;
using Android.Net;
using Android.Net.Wifi;

using System;
using System.Net;

using Outcoder.ComponentModel;
using Outcoder.Net;

namespace Outcoder.Services.Implementation
{
	public class NetworkMonitoringService : ObservableObject, INetworkMonitoringService
	{
		const int DefaultSampleRateMs = 1000;
		WifiReceiver wifiReceiver;
		int sampleRateMs;

		public int SampleRateMs
		{
			get
			{
				return sampleRateMs;
			}
		}

		bool approachingDataLimit;

		public bool ApproachingDataLimit
		{
			get
			{
				return approachingDataLimit;
			}
			private set
			{
				bool temp = LimitData;
				if (Assign(ref approachingDataLimit, value) == AssignmentResult.Success)
				{
					if (temp != LimitData)
					{
						OnPropertyChanged(nameof(LimitData));
					}
				}
			}
		}

		bool roaming;

		public bool Roaming
		{
			get
			{
				return roaming;
			}
			private set
			{
				bool temp = LimitData;
				if (Assign(ref roaming, value) == AssignmentResult.Success)
				{
					if (temp != LimitData)
					{
						OnPropertyChanged(nameof(LimitData));
					} 
				}
			}
		}

		public virtual bool LimitData
		{
			get
			{
				return Roaming || ApproachingDataLimit;
			}
		}

		public NetworkConnectionType NetworkConnectionType { get; private set; }
		public event EventHandler<EventArgs> NetworkConnectionChanged;

		bool connected;

		public bool Connected
		{
			get
			{
				return connected;
			}
			set
			{
				Assign(ref connected, value);
			}
		}

		bool IsConnected(ConnectivityManager connectivityManager)
		{
			NetworkInfo info = connectivityManager.ActiveNetworkInfo;
			return info != null && info.IsConnected;
		}

		public NetworkMonitoringService(int sampleRateMs = DefaultSampleRateMs)
		{
			this.sampleRateMs = sampleRateMs;

			Update();

			try
			{
				wifiReceiver = new WifiReceiver(this);
				var context = Application.Context;
				context.RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.NetworkStateChangedAction));
			}
			catch (Exception ex)
			{
				throw new Exception("Unable to start NetworkMonitoringService. " +
									"Please ensure that you have set the permission in your manifest. " +
									"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />", ex);
			}
		}

		internal void HandleNetworkStatusChanged(object sender)
		{
			Update();

			UISynchronizationContext.Instance.InvokeIfRequired(() =>
				{
					NetworkConnectionChanged?.Invoke(this, EventArgs.Empty);

					IMessenger messenger;
					if (Dependency.TryResolve<IMessenger>(out messenger))
					{
						messenger.Publish(new NetworkAvailabilityChangedMessage(
							new NetworkConnectionInfo(NetworkConnectionType, LimitData)));
					}
				});
		}

		string ssid;

		public string Ssid
		{
			get
			{
				return ssid;
			}
			set
			{
				Assign(ref ssid, value);
			}
		}

		string GetSsid(WifiManager wifiManager = null)
		{
			if (wifiManager == null)
			{
				var context = Application.Context;
				wifiManager = (WifiManager)context.GetSystemService(Context.WifiService);
			}

			WifiInfo wifiInfo = wifiManager.ConnectionInfo;
			var result = wifiInfo.ToString();

			return result;
		}

		public void Update()
		{
			var context = Application.Context;
			var wifi = (WifiManager)context.GetSystemService(Context.WifiService);
			ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
			Connected = IsConnected(cm);
			NetworkInfo info = cm.ActiveNetworkInfo;
			Roaming = info?.IsRoaming ?? false;
			Ssid = GetSsid(wifi);
			IPAddress = GetIPAddress();

			if (info != null && info.IsConnected)
			{
				if (info.Type == ConnectivityType.Wifi)
				{
					NetworkConnectionType = NetworkConnectionType.Lan;
				}
				else
				{
					NetworkConnectionType = NetworkConnectionType.MobileBroadband;
				}
			}
			else
			{
				NetworkConnectionType = NetworkConnectionType.None;
			}
		}

		string GetIPAddress()
		{
			IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
			string ipAddress = null;
			if (addresses != null && addresses[0] != null)
			{
				ipAddress = addresses[0].ToString();
			}

			return ipAddress;
		}

		string iPAddress;

		public string IPAddress
		{
			get
			{
				return iPAddress;
			}
			private set
			{
				Assign(ref iPAddress, value);
			}
		}
	}

	public class WifiReceiver : BroadcastReceiver
	{
		NetworkMonitoringService networkMonitoringService;

		public WifiReceiver(NetworkMonitoringService networkMonitoringService)
		{
			this.networkMonitoringService = ArgumentValidator.AssertNotNull(networkMonitoringService, "networkMonitoringService");
		}

		public override void OnReceive(Context context, Intent intent)
		{
			networkMonitoringService.HandleNetworkStatusChanged(this);

			//var wifi = (WifiManager)context.GetSystemService(Context.WifiService);
			//var state = wifi.WifiState;
			//			int wifiState = intent.GetIntExtra(WifiManager.ExtraWifiState, WifiState.Unknown);
			//		string wifiStateText = "No State";
			//
			//		switch (wifiState)
			//		{
			//			case WifiManager.WifiStateDisabling:
			//				wifiStateText = "WIFI_STATE_DISABLING";
			//				break;
			//			case WifiManager.WIFI_STATE_DISABLED:
			//				wifiStateText = "WIFI_STATE_DISABLED";
			//				break;
			//			case WifiManager.WIFI_STATE_ENABLING:
			//				wifiStateText = "WIFI_STATE_ENABLING";
			//				break;
			//			case WifiManager.WIFISTATEENABLED:
			//				wifiStateText = "WIFI_STATE_ENABLED";
			//				break;
			//			case WifiManager.WifiStateUnknown:
			//				wifiStateText = "WIFI_STATE_UNKNOWN";
			//				break;
			//			default:
			//				break;
		}
	}
}
#endif